package cn.ryh.rabbitmq.code.simple;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author Raoyh
 * @Description
 * @create 2022-07-08 17:04
 */
@Slf4j
public class Consumer {
    public static void main(String[] args) {
        // 所有的中间件都是基于TCP/IP协议基础上构建新型的协议规范，只不过rabbitMQ遵循的是AMQP
        // ip port
        // 1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.98.34.119");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("admin");
        factory.setPassword("XXXXXXX");
        Connection connection = null;
        Channel channel = null;
        try {
            // 2、创建连接Connection
            connection = factory.newConnection("消费者");
            // 3、通过连接创建通道Channel
            channel = connection.createChannel();
            // 4、通过通道Channel 创建交互机，声明队列，绑定关系，路由key,发生消息,接收消息
            String queueName = "simpleQueueName";
            channel.basicConsume(queueName, true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    log.info("收到的消息是：{}", new String(message.getBody(), StandardCharsets.UTF_8));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {
                    log.info("获取失败");
                }
            });

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(channel) && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
